package com.ktjy.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component // 组件类 - 交给Spring容器管理
@Aspect // 切面类
public class TransactionAspect {
    private static Logger log = LoggerFactory.getLogger(LoggerAspect.class);

    @Pointcut("execution(* com.ktjy.service.*.*(..))")
    private void pt() {
    }

    /**
     * 前置增强-打开数据库连接开启事务
     */
    @Before("pt()")
    public void before(JoinPoint jp) {
        log.info("[TransactionAspect 前置增强] 模拟打开数据库连接并开启事务...");
        log.info("SqlSession sqlSession = sqlSessionFactory.openSession(false);");
    }

    /**
     * 后置运行增强-提交事务
     */
    @AfterReturning(value = "pt()", returning = "result")
    public void afterReturning(JoinPoint jp, Object result) {
        log.info("[TransactionAspect 后置运行增强] 模拟正常完成业务操作,提交事务...");
        log.info("Sqlsession.commit();");
    }

    /**
     * 异常抛出增强-回滚事务
     */
    @AfterThrowing(value = "pt()", throwing = "e")
    public void afterThrowing(JoinPoint jp, Throwable e) {
        log.info("[TransactionAspect 异常抛出增强] 模拟异常,回滚事务,异常信息为:" + e.getMessage());
        log.info("Sqlsession.rollback();");
    }

    /**
     * 最终增强-关闭数据库连接
     */
    @After("pt()")
    public void after(JoinPoint jp) {
        log.info("[TransactionAspect 最终增强] 模拟关闭数据库连接...");
        log.info("Sqlsession.close();");
    }
}
